package cn.xxstudy.visitshop.ui.activity.main

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import cn.xxstudy.visitshop.R
import cn.xxstudy.visitshop.ui.activity.main.fragment.home.HomeFragment
import cn.xxstudy.visitshop.ui.activity.main.fragment.interview.InterviewFragment
import cn.xxstudy.visitshop.ui.activity.main.fragment.person.PersonFragment
import cn.xxstudy.visitshop.ui.activity.main.fragment.train.TrainFragment
import cn.xxstudy.visitshop.ui.activity.main.fragment.visit.VisitFragment
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.bottomnavigation.LabelVisibilityMode
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.math.abs

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        bottomNav.labelVisibilityMode = LabelVisibilityMode.LABEL_VISIBILITY_LABELED

        contentViewPager?.apply {
            adapter = object : FragmentStateAdapter(this@MainActivity) {
                override fun getItemCount() = 5

                override fun createFragment(position: Int) = when (position) {
                    0 -> HomeFragment()
                    1 -> VisitFragment()
                    2 -> InterviewFragment()
                    3 -> TrainFragment()
                    else -> PersonFragment()
                }

            }
            //禁止滑动
            isUserInputEnabled = false
            offscreenPageLimit = 5
        }

        var currentIndex = 0
        bottomNav.setOnNavigationItemSelectedListener {
            val selectedIndex = when (it.itemId) {
                R.id.home -> 0
                R.id.visit -> 1
                R.id.interview -> 2
                R.id.train -> 3
                else -> 4
            }
            //相邻的启用滑动动画
            contentViewPager.setCurrentItem(selectedIndex, abs(currentIndex - selectedIndex) == 1)
            currentIndex = selectedIndex
            true
        }

        contentViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                bottomNav.menu.getItem(position).isCheckable = true
            }
        })

    }

}